﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CygwinPackageManager.Common
{
	public static class Utils
	{
		private const string LastActionsPath = @"\etc\setup\last-action";
		private const string InstalledPackagesDBPath = @"\etc\setup\installed.db";
		private const string BaseRegistryKey = @"SOFTWARE\Cygnus Solutions\Cygwin\mounts v2\/";
		private const string LastCachePath = @"\etc\setup\last-cache";
		private const string LastMirrorPath = @"\etc\setup\last-mirror";

		#region Installation Extentions
		public static string GetInstalledPackagesDBPath(string rootDirectory)
		{
			if (string.IsNullOrEmpty(rootDirectory))
				throw new ArgumentException();

			return string.Concat(rootDirectory, InstalledPackagesDBPath);
		}

		public static string GetRegistryKey(bool allUsers)
		{
			return string.Concat((allUsers) ? @"HKEY_LOCAL_MACHINE\" : @"HKEY_CURRENT_USER\", BaseRegistryKey);
		}

		public static string GetLastCachePath(string rootDirectory)
		{
			if (string.IsNullOrEmpty(rootDirectory))
				throw new ArgumentException();

			return string.Concat(rootDirectory, LastCachePath);
		}

		public static string GetLastMirrorPath(string rootDirectory)
		{
			if (string.IsNullOrEmpty(rootDirectory))
				throw new ArgumentException();

			return string.Concat(rootDirectory, LastMirrorPath);
		}

		public static string GetSetupIniPath(string cacheDirectory, string mirrorUri)
		{
			if (string.IsNullOrEmpty(cacheDirectory))
				throw new ArgumentException();

			if (string.IsNullOrEmpty(mirrorUri))
				throw new ArgumentException();

			string setupDir = GetSetupIniDirectory(cacheDirectory, mirrorUri);
			return string.Concat(setupDir, @"\setup.ini");
		}

		public static string GetSetupIniDirectory(string cacheDirectory, string mirrorUri)
		{
			if (string.IsNullOrEmpty(cacheDirectory))
				throw new ArgumentException();

			if (string.IsNullOrEmpty(mirrorUri))
				throw new ArgumentException();

			return string.Format(@"{0}\{1}", cacheDirectory, System.Web.HttpUtility.UrlEncode(mirrorUri));
		}
		#endregion

		#region Business Extensions
		public static string GetDetails(this IEnumerable<PackageInfo> packages)
		{
			string details = string.Empty;

			foreach (PackageInfo package in packages)
				details += string.Format("@ {0}: {1}{2}", package.Name, package.Details, Environment.NewLine);

			return details;
		}
		#endregion
	}
}
